var car = {
	carData : "",
	totalPrice : 0,
	couserPrice : 0
};

//购物车中课程数
car.total = function(){
	car.carData = localStorage.getItem("carData");
	if(car.carData!==null)
		car.carData = JSON.parse(car.carData);
	else
		car.carData = [];
}

//购物车列表
car.list = function(){	
	if(car.carData.length > 0){
	    template.helper('dateFormat', function (inp) {
	        if (inp !== "" && inp !== null) {
	            return inp.split(" ")[0];
	        }
	    });
	    
        template.helper('coursePriceFormat', function (inp) {
            if(inp!==""){
                return numeral(inp).format('0,0.00');
            }
        });
        
        //图片过滤器
        template.helper('pictureFormat', function (inp) {
           if(inp){
               return Feng.ctxPath+"/file/getImage/"+inp;
           }
           else{
               return "themes/img/pd/course_defult.jpg";
           }
        });
		
	    var outHtml = template("dataTmpl",car.carData);
        $(".aui-car-box-list ul").html(outHtml);
        $("#car-list").show();
		$(".full-screen-tip").hide();
	}
	else{
		$("#car-list").hide();
		$(".full-screen-tip").show();
	}
}

//选择课程
$(document).on("click",".goods-check",function(){
	car.count();
});

//全选
$("#AllCheck").on("click",function(){	
	if($(this)[0].checked){
		$("input.goodsCheck[type='checkbox']").each(function(){
			$(this)[0].checked = true;
		});
	}
	else{
		$("input.goodsCheck[type='checkbox']").each(function(){
			$(this)[0].checked = false;
		});
	}
	car.count();
});

//计算总价
car.count = function(){
	var totalPrice = 0.00;
	$("input.goodsCheck[type='checkbox']:checked").each(function(){
//		var price = parseInt($(this).attr("data-price"));
		var price = parseFloat($(this).val());
		totalPrice += price;
	});
	
	console.log(totalPrice);	
	$("#AllTotal").text(numeral(totalPrice).format('0,0.00'));
	
	var checkedLength = $(".goodsCheck:checked").length;
	var allCheckLength = $(".goodsCheck").length;
	if(checkedLength===allCheckLength && allCheckLength!=0){
		$("#AllCheck")[0].checked = true;
	}
	else{
		$("#AllCheck")[0].checked = false;
	}
}


function deleteItem(id){
	layer.confirm('是否删除课程', {icon: 10, title:'是否删除课程?'}, function(index){
       //判断课程是否添加
		var arryIndex = car.carData.findIndex(function (item) {
		    return item.id == id;
		});		
		
		if(arryIndex > -1){
			car.carData.splice(arryIndex,1);
			if(car.carData.length === 0){
				$(".full-screen-tip").show();
			}			
			localStorage.setItem("carData",JSON.stringify(car.carData));
			//移除课程
			$("#item_"+id).parents("li").remove();		
			car.count();
			
		}
		layer.close(index);
    });
}


//购物车结算
$(".settlement").on("click",function(){
	var checkedLength = $(".goodsCheck:checked").length;
	var courseData = [];
	if(checkedLength!==0)
	{
		//获取选中课程
		$(".goodsCheck:checked").each(function(){
			var id = $(this).attr("data-id"),
				num = $(this).attr("data-num"),
				actualPrice = $(this).val();
			var arryIndex = car.carData.findIndex(function (item) {
			    return item.id == id;
			});		
			//获取
			car.carData[arryIndex].purchaseTimesS = num;	
			car.carData[arryIndex].actualPrice = actualPrice;
			
			if(arryIndex>-1){
				courseData.push(car.carData[arryIndex]);
			}
		});		
		courseData = JSON.stringify(courseData);
		localStorage.setItem("courseData",courseData);
		car.isRegister();
	}
	else{
		Feng.info("你还没有选择课程");
	}	

});


//判断用户是否注册
car.isRegister = function(){  
	
    var ajax = new $ax(Feng.ctxPath+"/user/checkUserRegister", function(data){        
        if (data.success){
        	window.location.href="order.html";
        }
        else{
        	window.location.href="bind-phone.html?callbackUrl=order.html";
        }        
   },function(data){    	
        Feng.log("验证用户信息失败");       
    });
    ajax.set("id",Feng.userId);
    ajax.start();
}
	
	

//增加、减少课次
$(document).on("click",".minus",function(){
	var _this =$(this).parent().find('.num');
	car.countCourseNum(_this,"minus")
});

$(document).on("click",".plus",function(){
	var _this =$(this).parent().find('.num');
	car.countCourseNum(_this,'add')
});

//计算课次6
car.countCourseNum = function(_this,action){
	var num = parseInt(_this.text()),						//当前显示课次
		total = parseInt(_this.attr("data-total")), 		//总课次
		id =  parseFloat(_this.attr("data-id")),			//id
		totalPrice = parseFloat(_this.attr("data-tprice")),	//总价
		activityPrice = parseFloat(_this.attr("data-aprice")),//活动价
		price = _this.attr("data-price");//单价
	
	if(num===1 && action==="minus"){


		Feng.error("至少购买一次课");
		return;
	}
	else if(num===total && action==="add"){
		Feng.error("已为总课次");
		return;
	}	
	
	//计算价格
	if(action==="minus"){
		_this.text(--num);	
	}
	else{
		
		_this.text(++num);	
	}
	
	if(num === total){
		$("#item_"+id+" .price-1").hide();
		$("#item_"+id+" .price-2").show();
		$("#item_"+id+" .check").val(activityPrice || totalPrice);
	}
	else{
		$("#item_"+id+" .price-1 span").text(num*price);
		$("#item_"+id+" .price-1").show();
		$("#item_"+id+" .price-2").hide();
		$("#item_"+id+" .check").val(num*price);
	}
	$("#item_"+id+" .check")[0].checked = true;
	$("#item_"+id+" .check").attr("data-num",num);
	car.count();	
}

$(function(){
	car.total();
	car.list();
	
	$("#AllCheck")[0].checked = false;
});
